package com.micro.ai.template.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.template.dto.request.AgentCreateRequest;
import com.micro.ai.template.dto.request.AgentUpdateRequest;
import com.micro.ai.template.dto.response.AgentDTO;
import com.micro.ai.template.service.AgentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * Agent实例管理控制器
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/agents")
@Tag(name = "Agent管理", description = "基于模板创建和管理Agent实例")
public class AgentInstanceController {

    @Autowired
    private AgentService agentService;

    @PostMapping
    @PreAuthorize("hasAuthority('agent:create')")
    @Operation(summary = "创建Agent", description = "基于模板创建Agent实例")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功",
            content = @Content(schema = @Schema(implementation = AgentDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "模板不存在")
    })
    public ApiResponse<AgentDTO> createAgent(
            @RequestHeader("X-User-Id") String userId,
            @RequestHeader("X-Tenant-Id") String tenantId,
            @Valid @RequestBody AgentCreateRequest request) {
        log.info("创建Agent: userId={}, tenantId={}, agentName={}", 
                userId, tenantId, request.getAgentName());
        
        AgentDTO agent = agentService.createAgent(userId, tenantId, request);
        
        return ApiResponse.success("创建成功", agent);
    }

    @PutMapping("/{agentId}")
    @PreAuthorize("hasAuthority('agent:update')")
    @Operation(summary = "更新Agent", description = "更新Agent实例信息")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功",
            content = @Content(schema = @Schema(implementation = AgentDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Agent不存在"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<AgentDTO> updateAgent(
            @RequestHeader("X-User-Id") String userId,
            @RequestHeader("X-Tenant-Id") String tenantId,
            @Parameter(description = "Agent ID") @PathVariable String agentId,
            @Valid @RequestBody AgentUpdateRequest request) {
        log.info("更新Agent: userId={}, agentId={}", userId, agentId);
        
        AgentDTO agent = agentService.updateAgent(userId, tenantId, agentId, request);
        
        return ApiResponse.success("更新成功", agent);
    }

    @DeleteMapping("/{agentId}")
    @PreAuthorize("hasAuthority('agent:delete')")
    @Operation(summary = "删除Agent", description = "删除Agent实例")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Agent不存在"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权删除")
    })
    public ApiResponse<Void> deleteAgent(
            @RequestHeader("X-User-Id") String userId,
            @RequestHeader("X-Tenant-Id") String tenantId,
            @Parameter(description = "Agent ID") @PathVariable String agentId) {
        log.info("删除Agent: userId={}, agentId={}", userId, agentId);
        
        agentService.deleteAgent(userId, tenantId, agentId);
        
        return ApiResponse.<Void>success(null);
    }

    @GetMapping("/{agentId}")
    @Operation(summary = "获取Agent详情", description = "获取Agent实例的详细信息")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = AgentDTO.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Agent不存在")
    })
    public ApiResponse<AgentDTO> getAgent(
            @Parameter(description = "Agent ID") @PathVariable String agentId) {
        log.info("获取Agent详情: agentId={}", agentId);
        
        AgentDTO agent = agentService.getAgentById(agentId);
        
        return ApiResponse.success(agent);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询Agent", description = "分页查询Agent实例列表")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = Page.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误")
    })
    public ApiResponse<Page<AgentDTO>> listAgents(
            @RequestHeader("X-Tenant-Id") String tenantId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "状态") @RequestParam(required = false) String status) {
        log.info("分页查询Agent: tenantId={}, pageNum={}, pageSize={}", tenantId, pageNum, pageSize);
        
        Page<AgentDTO> page = agentService.listAgents(tenantId, pageNum, pageSize, status);
        
        return ApiResponse.success(page);
    }

    @GetMapping("/my")
    @Operation(summary = "我的Agent", description = "查询当前用户创建的所有Agent")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(schema = @Schema(implementation = Page.class))),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权")
    })
    public ApiResponse<Page<AgentDTO>> getMyAgents(
            @RequestHeader("X-User-Id") String userId,
            @RequestHeader("X-Tenant-Id") String tenantId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("查询我的Agent: userId={}, tenantId={}", userId, tenantId);
        
        Page<AgentDTO> page = agentService.getMyAgents(userId, tenantId, pageNum, pageSize);
        
        return ApiResponse.success(page);
    }

    @PostMapping("/{agentId}/health")
    @Operation(summary = "健康检查", description = "检查Agent实例的健康状态")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "健康检查完成"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Agent不存在")
    })
    public ApiResponse<Void> healthCheck(
            @Parameter(description = "Agent ID") @PathVariable String agentId) {
        log.info("Agent健康检查: agentId={}", agentId);
        
        agentService.healthCheck(agentId);
        
        return ApiResponse.<Void>success(null);
    }
}

